package com.ztgf.logistics.service.api;

import com.alibaba.fastjson.JSON;
import com.deppon.dop.module.sdk.shared.domain.result.ResultDO;
import com.deppon.dop.module.sdk.shared.util.HttpUtils;
import com.deppon.dop.module.sdk.shared.util.SecurityUtil;
import com.ztgf.common.utils.StrUtils;
import com.ztgf.logistics.models.bo.deppon.LogisticsHttpLogSaveBO;
import com.ztgf.logistics.models.bo.deppon.api.*;
import com.ztgf.logistics.models.service.deppon.IAsyncLogisticsOrderService;
import com.ztgf.logistics.models.service.deppon.ILogisticsHttpLogService;
import com.ztgf.logistics.models.vo.deppon.api.*;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.httpclient.NameValuePair;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Description:
 * @Author: mxli
 * @Date: 2021-10-19 10:24
 **/
@DubboService
@Slf4j
public class DepponServiceImpl implements IDepponService {

    @Value("${deppon-api.customer-code}")
    private String custCode;
    @Value("${deppon-api.sign}")
    private String sign;
    @Value("${deppon-api.company-code}")
    private String companyCode;
    @Value("${deppon-api.app-key}")
    private String appKey;
    @Value("${deppon-api.url.add-order}")
    private String addOrderApiUrl;
    @Value("${deppon-api.url.update-order}")
    private String updateOrderApiUrl;
    @Value("${deppon-api.url.save-cancle-order}")
    private String saveCancleOrderApiUrl;
    @Value("${deppon-api.url.query-order-list}")
    private String queryOrderListApiUrl;
    @Value("${deppon-api.url.query-website-list}")
    private String queryWebsiteListApiUrl;
    @Value("${deppon-api.url.save-budget-list}")
    private String saveBudgetApiUrl;

    @DubboReference
    private ILogisticsHttpLogService logisticsHttpLogService;
    @Resource
    @Lazy
    private IAsyncLogisticsOrderService asyncOrderService;


    /**
     * 添加订单
     * @param bo
     * @return
     */
    @Override
    public DepponAddOrderVO addOrder(DepponAddOrderBO bo) {
        String result = httpClient(addOrderApiUrl, bo);
        DepponAddOrderVO vo = null;
        if(StrUtils.isNotEmpty(result)){
            vo = JSON.parseObject(result, DepponAddOrderVO.class);
        }
        return vo;
    }

    /**
     * 修改订单
     * @param bo
     * @return
     */
    @Override
    public DepponResultVO updateOrder(DepponEditOrderBO bo) {
        String result = httpClient(updateOrderApiUrl, bo);
        DepponResultVO vo = null;
        if(StrUtils.isNotEmpty(result)){
            vo = JSON.parseObject(result, DepponResultVO.class);
        }
        return vo;
    }

    /**
     * 撤销订单
     * @param bo
     * @return
     */
    @Override
    public DepponResultVO saveCancleOrder(DepponCancleBO bo) {
        String result = httpClient(saveCancleOrderApiUrl, bo);
        DepponResultVO vo = null;
        if(StrUtils.isNotEmpty(result)){
            vo = JSON.parseObject(result, DepponResultVO.class);
        }
        return vo;
    }

    /**
     * 查询订单
     * @param bo
     * @return
     */
    @Override
    public DepponResultVO<DepponQueryOrderVO> queryOrderList(DepponQueryOrderBO bo) {
        String result = httpClient(queryOrderListApiUrl, bo, true);
        DepponResultVO<DepponQueryOrderVO> resultVO = null;
        if(StrUtils.isNotEmpty(result)){
            resultVO = JSON.parseObject(result, DepponResultVO.class);
        }
        return resultVO;
    }

    /**
     * 网点查询
     * @param bo
     * @return
     */
    @Override
    public DepponResultVO<DepponWebsiteListVO> queryWebsiteList(DepponWebsiteBO bo) {
        String result = httpClient(queryWebsiteListApiUrl, bo, false);
        DepponResultVO<DepponWebsiteListVO> resultVO = null;
        if(StrUtils.isNotEmpty(result)){
            resultVO = JSON.parseObject(result, DepponResultVO.class);
        }
        return resultVO;
    }

    /**
     * 试算
     * @param bo
     * @return
     */
    @Override
    public DepponResultVO<List<DepponBudgetVO>> saveBudget(DepponBudgetBO bo) {
        String result = httpClient(saveBudgetApiUrl, bo, true);
        DepponResultVO<List<DepponBudgetVO>> resultVO = null;
        if(StrUtils.isNotEmpty(result)){
            resultVO = JSON.parseObject(result, DepponResultVO.class);
        }
        return resultVO;
    }


    public String httpClient(String url, Object objParms){
        return httpClient(url, objParms, true);
    }


    public String httpClient(String url, Object objParms, boolean isAddLog){
        //订单内容 json字符串，SDK提供FastJsonUtil转Json
        String params= JSON.toJSONString(objParms);
        //companyCode与appkey为双方约定
//        String companyCode="this is companyCode";
//        String appkey="this is appkey";
        //时间戳 SDK提供SecurityUtil获取时间戳
        String timestamp= System.currentTimeMillis() + "";
        //摘要 SDK提供SecurityUtil生成摘要
        String digest=SecurityUtil.getAlibabaDigest(params+appKey+timestamp);
        //post请求参数
        NameValuePair[] data = new NameValuePair[4];
        data[0] = new NameValuePair("companyCode", companyCode);
        data[1] = new NameValuePair("digest", digest);
        data[2] = new NameValuePair("timestamp", timestamp);
        data[3] = new NameValuePair("params", params);
        //请求url
        ResultDO<String> response = new ResultDO<String>();
        try{
            response = HttpUtils.sendRequest(url, data, "UTF-8", 60000);
        } catch (Exception e) {
            log.error("http is error", e);
        }
        String result = response.getModel();

        //返回结果
        log.error(JSON.toJSONString(response));
        if(isAddLog){
            LogisticsHttpLogSaveBO saveBO = new LogisticsHttpLogSaveBO();
            saveBO.setBusinessNotes(url);
            saveBO.setParams(params);
            if(StrUtils.isNotEmpty(result)){
                result = result.replaceAll("\\n", "").replaceAll("\\t", "");
            }
            saveBO.setReturnValue(result);
            int status = 1;
            if(response != null && response.isSuccess()){
                status = 0;
            }
            saveBO.setStatus(status);
//            transactionCommitHandler.execute(()->{
//                //添加日志
//                logisticsHttpLogService.add(saveBO);
//            });

            //修改payOrderLog 状态
//            TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
//                @Override
//                public void afterCommit() {
//                    try{
//                        asyncOrderService.addDepponHttpLog(saveBO);
//                    } catch (ServiceException e) {
//                        log.error("添加日志失败", e);
//                    }
//                }
//            });
            asyncOrderService.addDepponHttpLog(saveBO);
//            transactionCommitHandler.handler(() -> {
//                logisticsHttpLogService.add(saveBO);
//            });

        }
        return result;
    }
}
